package location.pokemon.com.pokemongolocation.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import butterknife.InjectView;
import butterknife.OnClick;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import location.pokemon.com.pokemongolocation.R;
import location.pokemon.com.pokemongolocation.utils.LatLngUtils;
import location.pokemon.com.pokemongolocation.utils.SharePrefereceManager;
import location.pokemon.com.pokemongolocation.widgets.FloatClickListener;
import location.pokemon.com.pokemongolocation.widgets.FloatView;

public class WindowService extends Service implements LocationListener, FloatClickListener {

    public static final float RUN_DISTANCE_DEFAULT = 3.f;
    public static final int RUN_CIRCLE = 0;
    public static final int RUN_RANDOM = 1;

    private double defaultMoveValue = 3.0E-4d;
    private int forbidCount = 0;
    private int forbidDirection;
    private double latitude = 31.3029742001d;
    private LocationManager locationManager;
    private double longitude = 120.60971259d;
    private boolean mAutoPause = false;
    private boolean mAutoStart = false;
    private FloatView mFloatView;

    private int mRunMode;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (WindowService.this.mAutoStart) {
                if (mRunMode == RUN_CIRCLE) {
                    WindowService.this.genCircleRun();
                } else {
                    WindowService.this.genLocation();
                }
            }
        }
    };
    private int mPointCount = 0;
    private Random mRandom = new Random();
    private WindowManager mWindowManager;
    private LayoutParams wmParams;

    public void onCreate() {
        super.onCreate();
        initLocation();
        mRunMode = SharePrefereceManager.getInstance().getRunMode();
        defaultMoveValue = SharePrefereceManager.getInstance().getRunDistance() * 1E-5;
        if (SharePrefereceManager.getInstance().isDialogShow()) {
            Log.i("lwotr", "show dialog");
            createFloatView();
        } else {
            Log.i("lwtor", "auto run");
            onAutoTouch();
        }
    }

    private void createFloatView() {
        this.wmParams = new LayoutParams();
        this.mWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
        this.wmParams.type = LayoutParams.TYPE_PHONE;
        this.wmParams.format = PixelFormat.RGBA_8888;
        this.wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        this.wmParams.gravity = Gravity.START | Gravity.TOP;
        this.wmParams.x = 0;
        this.wmParams.y = 0;
        this.wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        this.wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

        mFloatView = new FloatView(this);
        mFloatView.setParams(wmParams);
        mFloatView.setOnFloatClickListener(this);
        this.mWindowManager.addView(mFloatView, this.wmParams);
    }

    private void initLocation() {
        this.latitude = Double.parseDouble(SharePrefereceManager.getInstance().getLat());
        this.longitude = Double.parseDouble(SharePrefereceManager.getInstance().getLng());
        if (ContextCompat.checkSelfPermission(this, "android.permission.ACCESS_FINE_LOCATION") == 0 || ContextCompat.checkSelfPermission(this, "android.permission.ACCESS_COARSE_LOCATION") == 0) {
            this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            try {
                this.locationManager.addTestProvider("gps", false, true, false, false, true, true, true, 0, 5);
                this.locationManager.setTestProviderEnabled("gps", true);
                this.locationManager.requestLocationUpdates("gps", 0, 0.0f, this);
                try {
                    resetLocation(this.longitude, this.latitude);
                } catch (Exception e) {
                    Log.e("service ", e.getMessage());
                }
            } catch (Exception e2) {
                Intent localIntent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(localIntent);
                Toast.makeText(this, R.string.loction_test, Toast.LENGTH_SHORT).show();
                stopSelf();
            }
        }
    }

    private void resetLocation(double longitude, double latitude) {
        Log.i("lwtor", "lat:" + latitude);
        Log.i("lwtor", "lng:" + longitude);
        this.latitude = latitude;
        this.longitude = longitude;
        Location mLocation = new Location("gps");
        mLocation.setTime(System.currentTimeMillis());
        mLocation.setLongitude(longitude);
        mLocation.setLatitude(latitude);
        mLocation.setAccuracy(3.0f);
        mLocation.setAltitude(2.0d);
        mLocation.setSpeed(1.0f);
        mLocation.setTime(System.currentTimeMillis());
        mLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
        this.locationManager.setTestProviderLocation("gps", mLocation);
        SharePrefereceManager.getInstance().putLocation(String.valueOf(longitude), String.valueOf(latitude));
    }

    public void onLeftTouch() {
        resetLocation(this.longitude - getMoveDistance(), this.latitude);
    }

    public void onRightTouch() {
        resetLocation(this.longitude + getMoveDistance(), this.latitude);
    }

    public void onUpTouch() {
        resetLocation(this.longitude, this.latitude + getMoveDistance());
    }

    public void onDownTouch() {
        resetLocation(this.longitude, this.latitude - getMoveDistance());
    }

    public void onAutoTouch() {
        if (this.mAutoStart) {
            this.mHandler.removeMessages(0);
            this.mAutoStart = false;
            mFloatView.setLeftTopText(getString(R.string.auto));
            this.mPointCount = 0;
            return;
        }
        resetLocation(LatLngUtils.getlng(0), LatLngUtils.getLat(0));
        this.mHandler.sendEmptyMessageDelayed(0, (long) (this.mRandom.nextInt(300) + 1000));
        this.mAutoStart = true;
        mFloatView.setLeftTopText(getString(R.string.cancel));
    }

    public void onPauseTouch() {
        if (this.mAutoPause) {
            this.mAutoPause = false;
            mFloatView.setRightTopText(getString(R.string.pause));
            this.mHandler.sendEmptyMessageDelayed(0, 1000);
            this.mAutoStart = true;
            return;
        }
        this.mAutoPause = true;
        mFloatView.setRightTopText(getString(R.string.resume));
        this.mHandler.removeMessages(0);
        this.mAutoStart = false;
    }

    private void genCircleRun() {
        resetLocation(LatLngUtils.getlng(this.mPointCount), LatLngUtils.getLat(this.mPointCount));
        this.mPointCount++;
        this.mHandler.sendEmptyMessageDelayed(0, (long) (this.mRandom.nextInt(500) + 1000));
    }

    private void genLocation() {
        boolean z = true;
        int direction = this.mRandom.nextInt(4);
        if (this.forbidCount == 0) {
            Log.i("lwtor", "reset forbid direction,current direction:" + direction);
            this.forbidCount = 30;
            switch (direction) {
                case 0:
                    this.forbidDirection = 3;
                    break;
                case 1:
                    this.forbidDirection = 2;
                    break;
                case 2:
                    this.forbidDirection = 1;
                    break;
                case 3:
                    this.forbidDirection = 0;
                    break;
            }
            Log.i("lwtor", "forbid direction:" + this.forbidDirection);
        }
        String str = "lwtor";
        StringBuilder append = new StringBuilder().append("direction:").append(direction).append(", forbid direction:").append(this.forbidDirection).append(", equals:");
        if (direction != this.forbidDirection) {
            z = false;
        }
        Log.i(str, append.append(z).toString());
        if (direction == this.forbidDirection) {
            Log.i("lwtor", "reset direction");
            switch (this.forbidDirection) {
                case 0:
                    direction = 3;
                    break;
                case 1:
                    direction = 2;
                    break;
                case 2:
                    direction = 1;
                    break;
                case 3:
                    direction = 0;
                    break;
            }
        }
        Log.i("lwtor", "new direction:" + direction);
        this.forbidCount--;
        switch (direction) {
            case 0:
                onLeftTouch();
                break;
            case 1:
                onUpTouch();
                break;
            case 2:
                onRightTouch();
                break;
            case 3:
                onDownTouch();
                break;
        }
        this.mHandler.sendEmptyMessageDelayed(0, 500);
    }

    private double getMoveDistance() {
        return this.defaultMoveValue;
    }

    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public void onLocationChanged(Location location) {
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    public void onProviderEnabled(String provider) {
    }

    public void onProviderDisabled(String provider) {
    }

    public void onDestroy() {
        super.onDestroy();
        this.mWindowManager.removeView(this.mFloatView);
    }

    @Override
    public void onWestClick() {
        onLeftTouch();
    }

    @Override
    public void onEastClick() {
        onRightTouch();
    }

    @Override
    public void onNorthClick() {
        onUpTouch();
    }

    @Override
    public void onSouthClick() {
        onDownTouch();
    }

    @Override
    public void onLeftTopClick() {
        onAutoTouch();
    }

    @Override
    public void onRightTopClick() {
        onPauseTouch();
    }
}